import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/image_picker_widget.dart';
import 'package:kxy_flutter_app/components/loading_dialog.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/cert.dart';
import 'package:select_dialog/select_dialog.dart';

class CertDetailView extends StatefulWidget {
  final String certId;

  const CertDetailView({Key key, this.certId}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return CertDetailViewState();
  }
}

class CertDetailViewState extends State<CertDetailView> {
  Cert cert;
  bool isEdit;
  List<Map<String, dynamic>> certTypeModelList;
  List<String> certTypeList;
  List<String> certNameList;
  LoadingDialog loading;

  Future loadCertFuture;
  DateFormat dateFormat = new DateFormat('yyyy/MM/dd');

  @override
  void initState() {
    loading = new LoadingDialog(context);
    isEdit = widget.certId != null && widget.certId.isNotEmpty;
    loadCertFuture = loadCert();
    super.initState();
  }

  Future loadCert() async {
    if (isEdit) {
      var certRes = await Http.instance.post('/usercenter-app/cert/info/${widget.certId}');
      this.cert = Cert.fromJson(certRes.data);
    } else {
      cert = new Cert();
    }

    var certTypeRes = await Http.instance.post(
      '/usercenter-app/dict/type',
      params: {'type': 'CERTTYPE'},
    );

    certTypeList = List<String>();
    certTypeModelList = List<Map<String, dynamic>>();
    (certTypeRes.data as List).forEach((type) {
      certTypeModelList.add(type);
      certTypeList.add(type['label'].toString());
    });
    onCertTypeChange(cert.certType);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('证件详情'),
        actions: [
          FlatButton(
            child: Text('保存'),
            onPressed: save,
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: FutureBuilder(
        future: loadCertFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    return ListView(
      padding: EdgeInsets.fromLTRB(0, 5, 0, 10),
      children: [
        fieldItem(
          leading: leading('证件类型'),
          title: title(cert.certType ?? '请选择证件类型'),
          isRequired: true,
          onTap: () async {
            SelectDialog.showModal(
              context,
              label: '请选择证件类型',
              selectedValue: cert.certType,
              items: certTypeList,
              showSearchBox: false,
              onChange: (certType) {
                setState(() {
                  onCertTypeChange(certType);
                });
              },
            );
          },
        ),
        fieldItem(
          leading: leading('证件名称'),
          title: title(cert.certName ?? '请选择证件名称'),
          isRequired: true,
          onTap: () async {
            SelectDialog.showModal(
              context,
              label: '请选择证件名称',
              selectedValue: cert.certName,
              items: certNameList,
              showSearchBox: false,
              onChange: (certName) {
                setState(() {
                  cert.certName = certName;
                });
              },
            );
          },
        ),
        fieldItem(
          leading: leading('证件编号'),
          title: textField(
            cert.certNumber,
            (val) => cert.certNumber = val,
          ),
        ),
        fieldItem(
          leading: leading('专业类型'),
          title: textField(
            cert.specialty,
            (val) => cert.specialty = val,
          ),
        ),
        fieldItem(
          leading: leading('专业级别'),
          title: textField(
            cert.level,
            (val) => cert.level = val,
          ),
        ),
        fieldItem(
          leading: leading('技术等级'),
          title: textField(
            cert.skillLevel,
            (val) => cert.skillLevel = val,
          ),
        ),
        fieldItem(
          leading: leading('证件工种'),
          title: textField(
            cert.craft,
            (val) => cert.craft = val,
          ),
        ),
        fieldItem(
          leading: leading('发证日期'),
          title: title(formatDate(cert.certOpenDate)),
          onTap: () async {
            var date = await getDate(cert.certOpenDate);
            if (date != null) {
              cert.certOpenDate = date;
            }
          },
        ),
        fieldItem(
          leading: leading('有效期始'),
          title: title(formatDate(cert.certStartTime)),
          onTap: () async {
            var date = await getDate(cert.certStartTime);
            if (date != null) {
              setState(() {
                cert.certStartTime = date;
              });
            }
          },
        ),
        fieldItem(
          leading: leading('有效期末'),
          title: title(formatDate(cert.certEndTime)),
          onTap: () async {
            var date = await getDate(
              cert.certEndTime,
              lastDate: DateTime.parse('2030-01-01'),
            );
            if (date != null) {
              setState(() {
                cert.certEndTime = date;
              });
            }
          },
        ),
        fieldItem(
          leading: leading('复审时间'),
          title: title(formatDate(cert.certSecondTime)),
          onTap: () async {
            var date = await getDate(cert.certStartTime);
            if (date != null) {
              setState(() {
                cert.certSecondTime = date;
              });
            }
          },
        ),
        fieldItem(
          leading: leading('发证机构'),
          title: textField(
            cert.certAuthority,
            (val) => cert.certAuthority = val,
          ),
        ),
        fieldItem(
          leading: leading('操作项目'),
          title: textField(
            cert.remark,
            (val) => cert.remark = val,
          ),
        ),
        ListTile(
          leading: leading('正面照片'),
          title: Padding(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: ImagePickerWidget(
                initUrl: cert.photoFront,
                uploaded: (url) {
                  setState(() {
                    cert.photoFront = url;
                  });
                }),
          ),
        ),
        ListTile(
          leading: leading('反面照片'),
          title: Padding(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: ImagePickerWidget(
              quality: 80,
              initUrl: cert.photoBack,
              uploaded: (url) {
                setState(() {
                  cert.photoBack = url;
                });
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget fieldItem({Widget leading, Widget title, Function onTap, bool isRequired = false}) {
    return Container(
      constraints: BoxConstraints(minHeight: 50),
      padding: EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.black12, width: 0.5),
        ),
      ),
      child: Row(
        children: [
          Padding(
            padding: EdgeInsets.only(right: 15),
            child: leading,
          ),
          Expanded(
            child: InkWell(
              child: title,
              onTap: () {
                if (onTap != null) onTap();
              },
            ),
          ),
          if (isRequired)
            Text(
              '必填',
              style: TextStyle(
                fontSize: 12,
                color: Colors.red,
              ),
            ),
        ],
      ),
    );
  }

  Widget textField(String value, Function(String) onChange) {
    return TextField(
      onChanged: onChange,
      style: TextStyle(fontSize: 14, color: Colors.black),
      controller: new TextEditingController(text: value ?? ''),
      decoration: InputDecoration(border: InputBorder.none),
    );
  }

  String formatDate(DateTime dateTime) {
    if (dateTime == null) {
      return '请选择日期';
    }
    return dateFormat.format(dateTime);
  }

  Future<DateTime> getDate(DateTime initDate, {DateTime firstDate, DateTime lastDate}) async {
    FocusScope.of(context).requestFocus(FocusNode());
    return await showDatePicker(
      context: context,
      initialDate: initDate ?? DateTime.now(),
      firstDate: firstDate ?? DateTime.parse('1990-01-01'),
      lastDate: lastDate ?? DateTime.now(),
    );
  }

  Widget leading(String text) {
    return Text(
      text ?? '',
      style: TextStyle(
        color: Colors.black54,
      ),
    );
  }

  Widget title(String text) {
    return Text(
      text ?? '',
      style: TextStyle(
        color: Colors.black87,
        fontSize: 14,
      ),
    );
  }

  void onCertTypeChange(String certType) {
    if (certType == null) {
      certNameList = [];
      return;
    }
    cert.certType = certType;
    var stdCertIndex = certTypeList.indexOf(cert.certType);
    var remarks = certTypeModelList[stdCertIndex]['remarks'];
    if (remarks != null) {
      certNameList = remarks.toString().split(',');
    } else {
      certNameList = [];
    }
  }

  Future save() async {
    var url = isEdit ? '/usercenter-app/cert/update' : '/usercenter-app/cert/save';
    FocusScope.of(context).requestFocus(FocusNode());

    loading.show(text: '保存中');
    cert.userId = Auth.instance.userId;
    var res = await Http.instance.post(
      url,
      params: cert.toJson(),
    );

    loading.dismiss();
    if (res.code == 200) {
      Navigator.pop(context);
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }
  }
}
